import React, { Component } from 'react'
import FilterTitle from '../FilterTitle'
import FilterPicker from '../FilterSonone'
import FilterMore from '../FilterSontwo'
import styles from './index.module.css'
import { API } from '../../../../utils/api'
import { BASE_URL } from '../../../../utils/url'

// 标题高亮状态，初始化权威false
// true 表示高亮； false 表示不高亮
const titleSelectedStatus = {
  area: false,
  mode: false,
  price: false,
  more: false
}

// FilterPicker 和 FilterMore 组件的选中值
const selectedValues = {
  area: ['area', 'null'],
  mode: ['null'],
  price: ['null'],
  more: []
}
//筛选条件栏种的 ：父组件（主）
export default class Filter extends Component {

  state = {
    //高亮状态管理
    titleSelectedStatus,
    // 控制 FilterPicker 或 FilterMore 组件的展示或隐藏，当前组件是谁
    openType: '',
    // 所有筛选条件数据
    filtersData: {},
    // 筛选条件的选中值
    selectedValues:selectedValues
  }
 
  //标题栏点击事件
  //title组件传递触发点击事件的区域:函数改成箭头函数写法，从而获取上一级作用域种的this（不然this为underfine），也可以利用this指向
  //这里从子组件获取获取点击区域type的名称，从而可以设置高亮（传递给子组件）
  onTitleClick=(type)=>{
    this.bodyDom.className='bodyhidden'//body添加overflowhiiden解决滚动条bug
    
    const newtitleSelectedStatus={...this.state.titleSelectedStatus}//获得当前高亮值得对象

    // 遍历标题选中状态对象（当前选中的和有筛选的title，title高亮）
    Object.keys(newtitleSelectedStatus).forEach(key=>{
      const theSelected=this.state.selectedValues[key]

      if(key===type){//当前选中对象高亮，后面的有筛选值得高亮
        newtitleSelectedStatus[key] = true
      }else if(key==="area"&&(theSelected.length !== 2 || theSelected[0] !== 'area')){
        newtitleSelectedStatus[key] = true
      } else if((key==="mode"||key==="price")&&(theSelected[0] !== 'null')){
        newtitleSelectedStatus[key] = true
      }else if((key==="more")&&(theSelected.length !== 0)){
        newtitleSelectedStatus[key] = true
      }else {
        newtitleSelectedStatus[key] = false
      }
    }
    )
    this.setState({titleSelectedStatus:newtitleSelectedStatus,//更新高亮
    openType:type,//更新选中得title
  }

)
}

//点击事件取消对话框（传递给子组件）
onCancel =(type)=>{
  //判断当前窗口类似是否选中
  this.bodyDom.className=""//body添加overflowhiiden解决滚动条bug，清除
  const value=this.state.selectedValues[type]
  const {titleSelectedStatus}=this.state
  if(type==="area"&&(value.length !== 2 || value[0] !== 'area')){
    titleSelectedStatus[type] = true
  } else if((type==="mode"||type==="price")&&(value[0] !== 'null')){
    titleSelectedStatus[type] = true
  }else if((type==="more")&&(value.length !== 0)){
    titleSelectedStatus[type] = true
  }else {
    titleSelectedStatus[type] = false
  }
//更新状态
  this.setState({
    openType:" ",
    titleSelectedStatus:titleSelectedStatus,
  } )

}


//点击事件确定对话框（传递给子组件）
onSave=(type,value)=>{
  this.bodyDom.className=""//body添加overflowhiiden解决滚动条bug
  //value代表当前窗口类型传递得值（获取得赛选条件值）
  //type代表当前窗口类型（赛选类型）

  //确定了之后，判断当前窗口类似是否有赛选值（有的话title高亮）
  const {titleSelectedStatus}=this.state
  if(type==="area"&&(value.length !== 2 || value[0] !== 'area')){
    titleSelectedStatus[type] = true
  } else if((type==="mode"||type==="price")&&(value[0] !== 'null')){
    titleSelectedStatus[type] = true
  }else if((type==="more")&&(value.length !== 0)){
    titleSelectedStatus[type] = true
  }else {
    titleSelectedStatus[type] = false
  }
  //更新状态
  this.setState({
  selectedValues:{
    ...this.state.selectedValues,
    [type]:value,
  },
  openType:" ",
  titleSelectedStatus:titleSelectedStatus
  })
  //以下进行筛选值处理
  //获取目前筛选条件得值
  const newselectvalues={...this.state.selectedValues,[type]:value}
  const { area, mode, price, more } = newselectvalues
  // 筛选条件数据
  const filters = {}
  // 区域
  const areaKey = area[0]
  let areaValue = 'null'
  if (area.length === 3) {
    areaValue = area[2] !== 'null' ? area[2] : area[1]
  }
  filters[areaKey] = areaValue
  filters.mode = mode[0]// 方式和租金
  filters.price = price[0]
  filters.more = more.join(',')// 更多筛选条件 more

  //传给父组件
  this.props.getfiler(filters)

}


//请求数据：
async getfileronedata(){
  const {value}=JSON.parse(localStorage.getItem("hkzf_city"))
  const res = await API.get( `/houses/condition?id=${value}`)
  //获取筛选条件
  this.setState({
    filtersData:res.data.body
  })
}
componentDidMount(){
  this.getfileronedata();//初始化请求数据获取，
  this.bodyDom=document.body//获取body的dom节点
}

//渲染filerone组件的方法
renderfileronedata(){
  const {openType,filtersData,selectedValues} = this.state
  const defaultselect=selectedValues[openType]
  const {area,subway,rentType,price}=filtersData
  let data=[]
  let cols=3
  if(openType==="area"){
    data=[area,subway]
  }else if(openType==="mode"){
    data=rentType
    cols=1
  }else if(openType==="price"){
    data=price
    cols=1
  }

  if(openType==="area"||openType==="mode"||openType==="price")
  {return <FilterPicker key={openType} onCancel={this.onCancel} defaultselect={defaultselect} onSave={this.onSave} Type={openType} filtersData={data} cols={cols}/>}else{return (null)}

}

//渲染filertwo组件的方法
renderfilertwodata(){
  const {openType,filtersData,selectedValues} = this.state
  const {roomType,oriented,floor,characteristic}=filtersData
  const data={roomType,oriented,floor,characteristic}
  if(openType==="more"){
    return <FilterMore data={data} type={openType} onSave={this.onSave} onCancel={this.onCancel} selectedValues={selectedValues.more}></FilterMore>
  }
}


  render() {
    // 结构状态
    const { titleSelectedStatus,openType} = this.state
    return (
      <div className={styles.root}>
          {/* 前三个菜单的遮罩层展示逻辑 */}
          {(openType==="area"||openType==="mode"||openType==="price")?<div className={styles.mask} onClick={()=>this.onCancel(openType)} />:null}
        <div className={styles.content}>

          {/* 标题栏 */}
          <FilterTitle
            titleSelectedStatus={titleSelectedStatus}
            onClick2={this.onTitleClick}
          />

          {/* 前三个菜单对应的内容： */}
          {this.renderfileronedata()}

          {/* 最后一个菜单对应的内容： */}
          {this.renderfilertwodata()}

        </div>
      </div>
    )
  }
}
